<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <TreeTools :is-root="true" :tree-node="company" @addDept="addDept" />

        <!-- 树形组件 -->
        <el-tree :data="departs" :props="defaultProps">
          <!-- 传入插槽 -->
          <template v-slot="{ data }">
            <TreeTools
              :tree-node="data"
              @delDepts="getDepartments"
              @addDept="addDept"
              @editDept="editDept"
            />
          </template>
        </el-tree>
      </el-card>

      <!-- 弹出层 -->
      <AddDept ref="addDept" :show-dialog.sync="showDialog" :tree-node="node" @addDepts="getDepartments" />
    </div>
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import AddDept from './components/add-dept.vue'
import { getDepartments } from '@/api/departments'
import { transListToTreeData } from '@/utils/index'

export default {
  name: 'Departments',
  components: { TreeTools, AddDept },
  data() {
    return {
      departs: [], // 组织架构数据
      defaultProps: { lable: 'name' },
      company: {},
      showDialog: false,
      node: null, // 记录点击添加部门的对应那个部门
      loading: false // 用来控制进度弹层的显示和隐藏
    }
  },

  created() {
    this.getDepartments()
  },

  methods: {
    // 获取部门
    async getDepartments() {
      this.loading = true
      const res = await getDepartments()
      //   console.log(res)
      this.departs = transListToTreeData(res.depts, '')
      this.company = { id: '', name: res.companyName, manager: '负责人' }
      await new Promise(resolve => setTimeout(() => resolve(), 500))
      this.loading = false
    },

    // 添加子部门
    addDept(node) {
      this.showDialog = true
      this.node = node // 因为node是当前的点击的部门， 此时这个部门应该记录下来,
    },

    // 编辑部门
    async editDept(node) {
      this.node = node // 因为node是当前的点击的部门， 此时这个部门应该记录下来
      await this.$refs.addDept.getDepartmentDetail(node.id) // 直接调用子组件中的方法 传入一个id
      this.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
